class SocketMoudle {
  constructor (socketUrl) {
    this.currentSocketUrl = socketUrl
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = window.maxReconnectAttempts // 最大重连次数
    this.reconnectInterval = window.reconnectInterval // 重连间隔（毫秒）
    this.isManualClose = false // 是否手动关闭（不重连）

    // 绑定事件处理器
    this.ReiceiveDataHander = this.OnReceiveData.bind(this)
    this.openEventHander = this.openEvent.bind(this)
    this.CloseEvent = this.handleClose.bind(this)
    this.errorEvent = this.handleError.bind(this)
    this.endEvent = null
    console.log(window.maxReconnectAttempts)
    this.startSocket() // 初始化连接
  }

  // 启动/重启 WebSocket 连接
  startSocket () {
    if (this.ws) {
      this.ws.close() // 清理旧连接
    }

    console.log('正在连接：', this.currentSocketUrl)
    this.isManualClose = false // 重置手动关闭标志
    this.ws = new WebSocket(this.currentSocketUrl)

    this.ws.onopen = (e) => {
      this.reconnectAttempts = 0 // 重置重连计数
      this.openEventHander(e)
    }

    this.ws.onmessage = this.ReiceiveDataHander
    this.ws.onclose = this.CloseEvent
    this.ws.onerror = this.errorEvent
  }

  // 手动关闭连接（不触发重连）
  Close () {
    this.isManualClose = true
    if (this.ws) {
      console.log(this.currentSocketUrl, '主动关闭连接')
      this.ws.close()
      this.ws = null
    }
  }

  // 处理连接关闭事件（自动重连）
  handleClose (e) {
    console.log('连接断开', e.code, e.reason)
    if (!this.isManualClose && this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试第 ${this.reconnectAttempts} 次重连...`)
      setTimeout(() => this.startSocket(), this.reconnectInterval)
    } else if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error(`已达到最大重连次数（${this.maxReconnectAttempts}），停止重连`)
    }
    this.isManualClose = false // 重置手动关闭标志
  }

  // 处理错误事件
  handleError (e) {
    console.error('WebSocket 错误:', e)
    this.ws.close() // 触发 onclose 以启动重连
  }

  // 接收数据
  OnReceiveData (e) {
    this.endEvent?.(e.data)
  }

  // 连接成功回调
  openEvent (e) {
    console.log('连接成功', this.currentSocketUrl)
  }

  // 发送消息
  SendMessage (data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('发送消息：', data)
      this.ws.send(data)
    } else {
      console.error('WebSocket 未连接，消息发送失败')
    }
  }

  // 添加事件监听
  addEventListener (type, callback) {
    if (type === 'end') {
      this.endEvent = callback
    }
  }
}

export default SocketMoudle
